#include "MatrixDecompositionWindow.h"
#include "RenderWidget.h"
#include <Eigen>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>

MatrixDecompositionWindow::MatrixDecompositionWindow(QWidget *parent)
    : QWidget(parent)
    , render_(new RenderWidget(this))
{
    setupUi();
}

//ui设计
void MatrixDecompositionWindow::setupUi() {
    auto *mainLay = new QHBoxLayout(this);

    // 控制组
    ctrlGrp_ = new QGroupBox(tr("矩阵分解"), this);
    auto *vLay = new QVBoxLayout(ctrlGrp_);
    vLay->addWidget(new QLabel(tr("A11, A12:"), ctrlGrp_));
    le11_ = new QLineEdit(ctrlGrp_); le12_ = new QLineEdit(ctrlGrp_);
    vLay->addWidget(le11_); vLay->addWidget(le12_);
    vLay->addSpacing(10);
    vLay->addWidget(new QLabel(tr("A21, A22:"), ctrlGrp_));
    le21_ = new QLineEdit(ctrlGrp_); le22_ = new QLineEdit(ctrlGrp_);
    vLay->addWidget(le21_); vLay->addWidget(le22_);
    vLay->addSpacing(20);
    btnLU_    = new QPushButton(tr("LU 分解"), ctrlGrp_);
    btnQR_    = new QPushButton(tr("QR 分解"), ctrlGrp_);
    btnEigen_ = new QPushButton(tr("特征分解"), ctrlGrp_);
    vLay->addWidget(btnLU_); vLay->addWidget(btnQR_); vLay->addWidget(btnEigen_);
    vLay->addStretch();
    ctrlGrp_->setLayout(vLay);

    // 布局比例
    mainLay->addWidget(ctrlGrp_, 1);
    mainLay->addWidget(render_, 3);
    setLayout(mainLay);

    // 连接
    connect(btnLU_, &QPushButton::clicked, this, &MatrixDecompositionWindow::onLUPressed);
    connect(btnQR_, &QPushButton::clicked, this, &MatrixDecompositionWindow::onQRPressed);
    connect(btnEigen_, &QPushButton::clicked, this, &MatrixDecompositionWindow::onEigenPressed);
}

void MatrixDecompositionWindow::onLUPressed() {
    // 读取输入矩阵
    Eigen::Matrix2f A;
    A << le11_->text().toFloat(), le12_->text().toFloat(),
        le21_->text().toFloat(), le22_->text().toFloat();

    // 计算 LU 分解
    Eigen::FullPivLU<Eigen::Matrix2f> lu(A);
    Eigen::Matrix2f LU = lu.matrixLU();  // 下三角含 L（主对角默为1），上三角含 U

    // 提取 L（下三角加单位对角）
    Eigen::Matrix2f L = Eigen::Matrix2f::Identity();
    L.triangularView<Eigen::StrictlyLower>() = LU.triangularView<Eigen::StrictlyLower>();

    // 提取 U（上三角，包括主对角）
    Eigen::Matrix2f U = LU.triangularView<Eigen::Upper>();

    render_->showLU(L, U);
}


void MatrixDecompositionWindow::onQRPressed() {
    Eigen::Matrix2f A;
    A << le11_->text().toFloat(), le12_->text().toFloat(),
        le21_->text().toFloat(), le22_->text().toFloat();
    Eigen::HouseholderQR<Eigen::Matrix2f> qr(A);
    Eigen::Matrix2f Q = qr.householderQ();
    Eigen::Matrix2f R = qr.matrixQR().triangularView<Eigen::Upper>();
    render_->showQR(Q, R);
}

void MatrixDecompositionWindow::onEigenPressed() {
    Eigen::Matrix2f A;
    A << le11_->text().toFloat(), le12_->text().toFloat(),
        le21_->text().toFloat(), le22_->text().toFloat();
    Eigen::SelfAdjointEigenSolver<Eigen::Matrix2f> es(A);
    render_->showEigen(es.eigenvalues(), es.eigenvectors());
}
